<template>
  <div>
    <Modal
       v-model="modalShow"
      :styles="{ top: '60px' }"
      title="电子签名认证"
      footer-hide
      width="410"
    >
      <Form :label-width="100" :model="singForm" :rules="singFormRules" ref="singForm">
          <FormItem label="姓名" prop="fullname">
            <Input
              placeholder="请输入名称"
              :disabled="!edit"
              v-model="singForm.fullname"
            />
          </FormItem>
          <FormItem label="身份证" prop="card">
            <Input
              :disabled="!edit"
              placeholder="请输入身份证"
              v-model="singForm.card"
            />
          </FormItem>
          <FormItem label="本人手机号" prop="phonenumber">
            <Input
              :disabled="!edit"
              placeholder="请输入本人手机号"
              v-model="singForm.phonenumber"
            />
          </FormItem>
          <FormItem label="企业名称" prop="companyName">
            <Input
              :disabled="!edit"
              placeholder="请输入企业名称"
              v-model="singForm.companyName"
            />
          </FormItem>
          <FormItem label="电子签名" prop="signature">
            <div class="upload-list" v-if="singForm.signature">
              <template>
                <img :src="`${singForm.signature}`" />
                <div class="upload-list-cover">
                  <Icon
                    @click.native="handleImgPreview"
                    type="ios-eye-outline"
                  ></Icon>
                  <Icon
                    @click.native="handleRemoveImg"
                    type="ios-trash-outline"
                    v-if="modelType !== 'look' && edit===true"
                  ></Icon>
                </div>
              </template>
            </div>
            <Upload
              :format="['jpg','jpeg','png']"
              :on-format-error = "handleFormatError"
              :before-upload="handleBeforeUpload"
              :data="{userId:id}"
              :action="fileUploadUrl"
              :on-remove="handleFileRemove"
              :on-success="handleFileUpload"
              :show-upload-list="false"
              :headers="uploadHeader"
              name="sign"
              ref="upload"
            >
              <Button
                :disabled="!!singForm.signature"
                icon="ios-cloud-upload-outline"
                type="primary"
                >上传图片</Button
              >
            </Upload>
          </FormItem>
          <FormItem>
            <div v-show="edit">
              <Button @click="handleCancelClick">取消</Button>
              <Button style="margin-left:10px" type="primary" @click="handleOkClick">保存</Button>
            </div>
            <Button v-show="!edit" type="primary" @click="handleEdit">编辑</Button>
          </FormItem>
      </Form>
    </Modal>
    <Modal title="查看电子签名" v-model="imgViewVisible">
      <img
        :src="`${imgName}`"
        style="width: 100%"
        v-if="imgViewVisible"
      />
    </Modal>
  </div>
</template>

<script>

import {
  getUserSign,
  getUserInfo,
  saveUserSign
} from '@/api/staff.js';
import config from '@/config';
import { getHTTP, getToken } from '@/libs/util';

export default {
  model: {
    prop: 'value',
    event: 'on-visible-change'
  },
  props: {
    id: String | Number
  },
  data () {
    const validateCard = (rule, value, callback) => {
      let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
      let _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/;
      if (value === '') {
        callback(new Error('请输入身份证'));
      } else if (_IDRe18.test(value) || _IDre15.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确身份证号'));
      }
    };
    const validatePhone = (rule, value, callback) => {
      let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (value === '') {
        callback(new Error('请输入手机号码'));
      } else if (reg_tel.test(value)) {
        callback();
      } else {
        callback(new Error('请输入正确手机号'));
      }
    };
    return {
      edit: false,
      modalShow: false,
      userId: '', // 编辑时候
      singForm: {
        fullname: '', // 姓名
        signature: '', // 签名图片地址
        card: '',
        phonenumber: '',
        companyName: ''
      },
      singFormRules: {
        fullname: [{ required: true, message: '请输入名称' }],
        card: [{ validator: validateCard, trigger: 'blur' }],
        phonenumber: [{ validator: validatePhone, trigger: 'blur' }],
        companyName: [{ required: true, message: '请输入企业名称' }],
        signature: [{ required: true, message: '请上传电子签名' }]
      },
      fileUploadUrl: getHTTP() + `${config.baseUrl.pro}/fileupload/uploadsign`,
      roleList: [],
      jobList: [],

      // 图片上传
      imgName: '',
      imgViewVisible: false,
      uploadHeader: {
        Authorization: getToken()
      },

      swicthLoading: false,
      modalLoading: true, // 模态框数据加载
      resetButtonLoading: false,
      modelType: 'add',
      modelOkLoad: true, // 点击确定以后

      config
    };
  },
  mounted () {
  },
  methods: {
    show () {
      this.modalShow = true;
      this.edit = false;
    },
    // 切换编辑状态
    handleEdit () {
      this.edit = true;
    },
    // 电子签名
    async getUser (id) {
      const res = await getUserSign(id);
      this.singForm = res.data.data;
    },
    // 处理上传图片格式错误
    handleFormatError (file) {
      this.$Message.error('请上传后缀为jpeg,png,jpg图片');
    },
    // 上传前先验证图片大小小于5m
    handleBeforeUpload (file) {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.$Message.error('上传签名图片大小不能超过 5MB!');
      }
      return isLt5M;
      // console.log(this.singForm);
      // if (this.singForm.status != 'AUTH_SUCCESS') {
      //   this.$Message.error('未授权');
      //   return false;
      // }
    },
    handleFileUpload (response) {
      console.log(response, 'response');
      this.singForm.signature = response.data;
      this.handleResetModelLoading();
    },
    handleFileRemove () {
      this.singForm.signature = '';
    },
    handleOkClick () {
      this.$refs.singForm.validate(async valid => {
        const { fullname, phonenumber, card, signature, companyName } = this.singForm;
        if (valid) {
          const data = {
            userId: this.id,
            fullname,
            card,
            phonenumber,
            signature,
            companyName
          };
          const res = await saveUserSign(data);
          console.log('修改成功', res);
          this.modalShow = false;
          this.$emit('on-save-success');
        }
      });
    },
    handleResetModelLoading () {
      this.modelOkLoad = false;
      this.$nextTick(() => {
        this.modelOkLoad = true;
      });
    },
    handleCancelClick () {
      this.$refs.singForm.resetFields();
      this.modalShow = false;
    },
    handleImgPreview () {
      this.imgName = this.singForm.signature;
      this.imgViewVisible = true;
    },
    handleRemoveImg () {
      this.singForm.signature = '';
    },
    async getUserInfo (send) {
      await getUserInfo(send);
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .ivu-modal-body {
  //   padding: 30px 90px 20px 30px;
  padding-right: 30px;
}
.page-wrapper {
  .ivu-page {
    float: right;
    margin: 10px 0;
  }
}
.form-item-wrapper {
  display: flex;
  > .ivu-form-item {
    width: 50%;
  }
}
.upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.upload-list img {
  width: 100%;
  height: 100%;
}
.upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.upload-list:hover .upload-list-cover {
  display: block;
}
.upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
